Simplify Context Usage with a Custom Hook

When using the Context API in multiple components, you can streamline access by creating a custom hook for your context. This tiny hack reduces boilerplate and makes accessing context data more concise


Instead of using useContext directly every time, create a custom hook:

1. Define the Context and Provider:

import React, { createContext, useContext, useState } from 'react';

const ThemeContext = createContext();

export function ThemeProvider({ children }) {
    const [theme, setTheme] = useState("light");
    return (
        <ThemeContext.Provider value={{ theme, setTheme }}>
            {children}
        </ThemeContext.Provider>
    );
}

2. Create a Custom Hook:

export function useTheme() {
    return useContext(ThemeContext);
}

3. Use the Custom Hook in Components:

function ThemedComponent() {
    const { theme, setTheme } = useTheme();
    return (
        <div style={{ background: theme === "light" ? "#fff" : "#333", color: theme === "light" ? "#000" : "#fff" }}>
            <p>Current Theme: {theme}</p>
            <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
                Toggle Theme
            </button>
        </div>
    );
}

You Might Also Like

Labels: Names used to label loops and control flow

``` outerLoop: for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (j === 1) {...

Default Props for Components

This code sets a default value for the text prop in the Button component. If no text prop is provide...